package com.tac.se2_project2;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import android.provider.ContactsContract.Contacts;

public class MySqlDB {

	public final String CLOUD = "http://softeng.cs.uwosh.edu/students/severa24/";
	public final String FILE_NAME = "CloudZip.gz";
	public final String FILE_LOCATION = "/data/data/" + FILE_NAME;
	
	public static int bufferSize = 1024;
	
	public MySqlDB(){
		
	}  
    
    public void BackupAllContacts(Contact[] params) {
    	BufferedReader input=null;
        URL url = null;
        
        for(Contact contact : params){
	        try
	        {
	            url = new URL(CLOUD + "UploadContact.php?ContactId=" + contact.getID() + "&name=" + contact.getName().replaceAll(" ", "%20") +"&address=" + contact.get_address().replaceAll(" ", "%20") + "&phone=" + contact.getPhoneNumber().replaceAll(" ", "%20") + "&altPhone=" + contact.get_alt_number().replaceAll(" ", "%20") + "&email=" + contact.get_email().replaceAll(" ", "%20") + "&comment=" + contact.get_comment().replaceAll(" ", "%20") + "&userId=" + contact.get_userId() + "&categoryId=" + contact.get_cat());
	            
	            BufferedReader buff = new BufferedReader(new InputStreamReader(url.openStream()));
	            
	            String line = buff.readLine();
	            while (line != null){
	                line = buff.readLine();
	             }
	          } 
	        catch (MalformedURLException e)
	        { System.out.println("URL incorrectly formed");}
	        catch(IOException e)
	        {System.out.println(e.getMessage());}
	        finally
	        {
	            try
	            {
	                 if (input != null) input.close();
	            } catch(IOException e){}
	        }
        }
    }
    
    public void BackupAllCategories(Category[] params) {
    	BufferedReader input=null;
        URL url = null;
        
        for(Category cat : params){
	        try
	        {
	            url = new URL(CLOUD + "UploadCategory.php?name=" + cat.getName().replaceAll(" ", "%20") +"&userId=" + cat.get_userId() + "&categoryId=" + cat.getID());
	            
	            BufferedReader buff = new BufferedReader(new InputStreamReader(url.openStream()));
	            
	            String line = buff.readLine();
	            while (line != null){
	                line = buff.readLine();
	             }
	          } 
	        catch (MalformedURLException e)
	        { System.out.println("URL incorrectly formed");}
	        catch(IOException e)
	        {System.out.println(e.getMessage());}
	        finally
	        {
	            try
	            {
	                 if (input != null) input.close();
	            } catch(IOException e){}
	        }
        }
    }
    
    public void RemoveData(int userId){
    	BufferedReader input=null;
        URL url = null;

        try
        {
            url = new URL(CLOUD + "RemoveData.php?userId=" + userId);
            
            BufferedReader buff = new BufferedReader(new InputStreamReader(url.openStream()));
            
            String line = buff.readLine();
            while (line != null){
                line = buff.readLine();
             }
          } 
        catch (MalformedURLException e)
        { System.out.println("URL incorrectly formed");}
        catch(IOException e)
        {System.out.println(e.getMessage());}
        finally
        {
            try
            {
                 if (input != null) input.close();
            } catch(IOException e){}
        }
    }
    
    public boolean CheckUsernameExists(String username){
    	BufferedInputStream input=null;
        URL url = null;
        boolean isDuplicate = false;
        try
        {
            url = new URL(CLOUD + "CheckUsernameExists.php?username=" + username);
            
            BufferedReader buff = new BufferedReader(new InputStreamReader(url.openStream()));
            
            String line = buff.readLine();
            while (line != null){
                if(line.equalsIgnoreCase(username)){
                	isDuplicate = true;
                }
                line = buff.readLine();
             }
          } 
        catch (MalformedURLException e)
        { System.out.println("URL incorrectly formed");}
        catch(IOException e)
        {System.out.println(e.getMessage());}
        finally
        {
            try
            {
                 if (input != null) input.close();
            } catch(IOException e){}
        }
        return isDuplicate;
    }
    
    public int CheckUsernamePasswordValid(String username, String password){
    	BufferedInputStream input=null;
        URL url = null;
        String[] values = new String[4];
        int valid = -1;
        try
        {
            url = new URL(CLOUD + "GetUsernamePasswordSalt.php?username=" + username);
            
            BufferedReader buff = new BufferedReader(new InputStreamReader(url.openStream()));
            
            int count = 0;
            String line = buff.readLine();
            while (line != null){
                values[count] = line;
                count++;
                line = buff.readLine();
             }
          } 
        catch (MalformedURLException e)
        { System.out.println("URL incorrectly formed");}
        catch(IOException e)
        {System.out.println(e.getMessage());}
        finally
        {
            try
            {
                 if (input != null) input.close();
            } catch(IOException e){}
        }
        if(values[0] != null){
        	if(values[1].equalsIgnoreCase( PasswordHasher.md5(password + values[2]))){
        		valid = Integer.parseInt(values[3]);
        	}
        }
        return valid;
    }
    
    public Contact[] GetAllContacts(int userId){
    	BufferedInputStream input=null;
        URL url = null;
        Contact[] conts;
        List<Contact> contacts = new ArrayList<Contact>();
        int catsCount = 0;
        try
        {
            url = new URL(CLOUD + "GetContacts.php?userId=" + userId);
            
            BufferedReader buff = new BufferedReader(new InputStreamReader(url.openStream()));
            Contact con = null;
            int count = 0;
            String line = buff.readLine();
            while (line != null){
            	if(count == 0){
            		con = new Contact();
            		con.setName(line);
            		count++;
            	}
            	else if(count == 1){
            		con.setID(Integer.parseInt(line));
            		count++;
            	}
            	else if(count == 2){
            		con.set_address(line);
            		count++;
            	}
            	else if(count == 3){
            		con.setPhoneNumber(line);
            		count++;
            	}
            	else if(count == 4){
            		con.set_alt_number(line);
            		count++;
            	}
            	else if(count == 5){
            		con.set_email(line);
            		count++;
            	}
            	else if(count == 6){
            		con.set_comment(line);
            		count++;
            	}
            	else if(count == 7){
            		con.set_cat(Integer.parseInt(line));
            		count++;
            	}
            	else if(count == 8){
            		con.setModifyDate(new Date(java.sql.Timestamp.valueOf(line).getTime()));
            		contacts.add(con);
            		count = 0;
            	}
                line = buff.readLine();
             }
          } 
        catch (MalformedURLException e)
        { System.out.println("URL incorrectly formed");}
        catch(IOException e)
        {System.out.println(e.getMessage());}
        finally
        {
            try
            {
                 if (input != null) input.close();
            } catch(IOException e){}
        }
        conts = new Contact[contacts.size()];
        for(int i = 0; i < conts.length; i ++){
        	Contact con = new Contact();
        	con = contacts.get(i);
        	conts[i] = con;
        }
        return conts;
    }
    
    public Category[] GetAllCategories(int userId){
    	BufferedInputStream input=null;
        URL url = null;
        Category[] cats = new Category[5];
        int catsCount = 0;
        try
        {
            url = new URL(CLOUD + "GetCategories.php?userId=" + userId);
            
            BufferedReader buff = new BufferedReader(new InputStreamReader(url.openStream()));
            Category cat = null;
            int count = 0;
            String line = buff.readLine();
            while (line != null){
            	if(count == 0){
            		cat = new Category();
            		cat.setID(Integer.parseInt(line));
            		count++;
            	}
            	else if(count == 1){
            		cat.setName(line);
            		cats[catsCount] = cat;
            		catsCount++;
            		count = 0;
            	}
                line = buff.readLine();
             }
          } 
        catch (MalformedURLException e)
        { System.out.println("URL incorrectly formed");}
        catch(IOException e)
        {System.out.println(e.getMessage());}
        finally
        {
            try
            {
                 if (input != null) input.close();
            } catch(IOException e){}
        }
        
        return cats;
    }
    
    public int InsertNewUser(String username, String password, String salt){
    	BufferedReader input=null;
        URL url = null;
        int userId = -1;

        try
        {
            url = new URL(CLOUD + "InsertNewUser.php?username=" + username +"&password=" + password + "&salt=" + salt);
            
            BufferedReader buff = new BufferedReader(new InputStreamReader(url.openStream()));
            
            String line = buff.readLine();
            while (line != null){
                userId = Integer.parseInt(line);
                line = buff.readLine();
             }
          } 
        catch (MalformedURLException e)
        { System.out.println("URL incorrectly formed");}
        catch(IOException e)
        {System.out.println(e.getMessage());}
        finally
        {
            try
            {
                 if (input != null) input.close();
            } catch(IOException e){}
        }
        return userId;
    }
}
